<?php

namespace app\queue\stomp;

use support\ErrorCode;
use app\queue\BaseConsumer;
use Webman\Stomp\RetryAbleConsumer;
use common\exception\LogicException;
use common\model\ReviewFeedbackModel;

/**
 * 修改审核反馈权限状态
 */
class ChangeReviewFeedbackPermission extends BaseConsumer implements RetryAbleConsumer
{

    // 要消费的队列名
    public $queue = 'change_review_feedback_permission';

    // 连接名，对应 config/redis_queue.php 里的连接`
    public $connection = 'default';

    /**
     * 消费
     * @param $data
     * @throws \Throwable
     */
    public function doConsume($data)
    {
        try {
            APP_DEBUG && trace(var_export($data, true), 'DEBUG');
            $changeTime = $data['change_time'];
            $changeCompareField = $data['data_field'];
            $reviewFeedbackId = $data['review_feedback_id'];
            $changeTo = $data['change_to'];
            $reviewFeedback = model(ReviewFeedbackModel::class)->forceMasterDB()->find($reviewFeedbackId);
            if (empty($reviewFeedback)) {
                throw new LogicException('review feedback not found', ErrorCode::REVIEW_FEEDBACK_NOT_FOUND);
            }
            if ($reviewFeedback[$changeCompareField] != $changeTime) {
                throw new LogicException('execute time not equal', ErrorCode::DATA_INVALID);
            }
            $res = model(ReviewFeedbackModel::class)->modifyItem(['id' => $reviewFeedbackId, 'permissions' => $changeTo]);
            APP_DEBUG && trace(var_export($res, true), 'DEBUG');
        } catch (LogicException $e) {
            trace(format_exception_info($e), "ERR");
        } catch (\Throwable $e) {
            trace(format_exception_info($e), "ERR");
            throw $e;
        }
    }

    public function getTtr()
    {
        return 5;
    }

    public function canRetry($attempt, $error)
    {
        return $attempt <= 3;
    }
}
